package cn.ecpay.unionpay.settle.scheduled;

import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.Common.SFTPUtil;
import cn.ecpay.unionpay.settle.util.LogUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 *  定时下载对账文件
 *  每个小时的20分和50分别下载一次
 * Created by zhaoyanzeng on 2018/11/27.
 */
@Component
@PropertySource("classpath:FSTP.properties")
public class DownloadCheckFileService {
    @Resource
    private SFTPUtil sftp;
    @Value("${fstp.remote.path}")
    private String remotePath;
    @Value("${fstp.local.path}")
    private String localPath;
    @Scheduled(cron = "0 20/30 * * * ?")
    public void download(){
        LogUtil.writeLog("---开始下载文件---");
        sftp.login();
        byte[] buff = new byte[0];
        try {
            String wordDay = DateUtil.getDateTo8(new Date());
            LogUtil.writeLog("---远程文件目录:" + remotePath + wordDay +" ----");
            LogUtil.writeLog("---本地文件目录:" + localPath + wordDay +  " ----");
            String  prefix = getFileNamePrefix();
            String downloadFileName1 = prefix + "_49984517_0000300000000371";
            LogUtil.writeLog(downloadFileName1);
            String downloadFileName2 = prefix + "_49984517_0000300000000372";
            LogUtil.writeLog(downloadFileName2);
            String downloadFileName3 = prefix + "_49984517_0000300000000373";
            LogUtil.writeLog(downloadFileName3);
            sftp.download( remotePath + wordDay, downloadFileName1,localPath + wordDay + "/" );
            sftp.download( remotePath + wordDay, downloadFileName2,localPath + wordDay + "/" );
            sftp.download( remotePath + wordDay, downloadFileName3,localPath + wordDay + "/" );
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            sftp.logout();
        }
        LogUtil.writeLog("---下载完成----");
        String retStr = null;
        try {
            retStr = new String(buff,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(retStr);
    }

    public String getFileNamePrefix(){
        String fileDate = DateUtil.getDateTo6(new Date());
        int currentHour = DateUtil.getHour(new Date());
        int currentMinute = DateUtil.getMinute(new Date());
        int index = currentMinute > 30 ? (currentHour * 2 + 1) : currentHour * 2  ;
        String indexStr = index> 9 ? ""+index : "0"+index ;
        String fileNameMinute =  currentMinute > 30 ? "30":"00";
        String hourStr = currentHour>9? "" + currentHour:"0" + currentHour;
        return "IND"+ fileDate + indexStr + "VACD"+ hourStr + fileNameMinute;
    }
}
